/**
 * Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
 * All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are NOT permitted except as agreed by
 * iAuto (Shanghai) Co., Ltd.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */
import React, { useState, useEffect, useMemo } from 'react';
import { Checkbox } from 'antd';
import { CheckboxValueType } from 'antd/es/checkbox/Group';

const { Group } = Checkbox;

export interface IDateCustom {
  value?: string;
  format: string;
  onChange?: (value: string) => void;
}

const valueMap = new Map<string, string>();

const DateCustom: React.FC<IDateCustom> = (props) => {
  const [values, setValues] = useState<CheckboxValueType[]>([]);

  const handleChange = (checkedValue: CheckboxValueType[]) => {
    setValues(checkedValue);
    const value = checkedValue
      .sort((a: CheckboxValueType, b: CheckboxValueType) => a - b)
      .map((val) => valueMap.get(val as string))
      .join(',');
    props.onChange?.(value);
  };

  useEffect(() => {
    if (props.value) {
      const newValues = props?.value.split(',').map((val) => valueMap.get(val as string)) || [];
      setValues(newValues as CheckboxValueType[]);
    }
  }, [props.value]);

  const checkboxList = useMemo(() => {
    valueMap.clear();
    return (props.format?.split('*') || []).map((item: string) => {
      const [text, value] = item.split(':');
      valueMap.set(value, text);
      valueMap.set(text, value);
      return {
        text,
        value,
      };
    });
  }, [props.format]);

  return (
    <Group value={values} onChange={handleChange}>
      {checkboxList.map((item) => (
        <Checkbox key={item.value} value={item.value}>
          {item.text}
        </Checkbox>
      ))}
    </Group>
  );
};

export default DateCustom;
